Categories
JavaScript Basics

JavaScript Cheat Sheet — Operators and Dates

Spread the love

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Operators

We can do arithmetic with JavaScript.

We add with + and subtract with - :

let a = b + c - d;

We multiply with * and divide with / :

let a = b * (c / d);

And we get the remainder of one number divided by another with / :

let x = 100 % 48;

We increment with ++ :

a++;

And we decrement with -- :

b--;

Typeof

We can get type of primitive values and objects with typeof :

typeof a

It’s mostly useful for primitive values since it returns 'object' for all objects.

Assignment

We assign one value to a variable with = :

let x = 10

The right expression is assigned to the variable on the left.

a +=b is short for a = a + b . We can also replace + with - , * and / .

Comparison

We compare equality with === :

a === b

We check for inequality with !== :

a !== b

We check if a is greater than b with:

a > b

And we check if a is less than b with:

a < b

We can check for less than or equal with:

a <= b

And we check for greater than or equal with:

a >= b

Logical AND is && :

a && b

And logical OR is || :

a || b

Dates

We can create date objects with the Date constructor:

let d = new Date("2017-06-23");

If we omit the month and day, then it’s set to January 1:

let d = new Date("2017");

We can add the hour, minutes, and seconds with:

let d = new Date("2017-06-23T12:00:00-09:45");

Human readable date also works:

let d1 = new Date("June 23 2017");
let d2 = new Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)");

A date object comes with methods to let us get various values from it.

We call them by writing:

let d = new Date();
let a = d.getDay();

getDay() gets the day of the week

getDate() gets the day of the month as a number.

getFullYear() gets the 4 digit year.

getHours() gets the hours.

getMilliseconds() gets the milliseconds.

getMinutes() gets the minutes.

getMonth() gets the month.

getSeconds() gets the seconds.

getTime() gets the milliseconds since 1970, January 1.

We can also set values with some setter methods.

To call them, we write:

let d = new Date();
d.setDate(d.getDate() + 7);

setDay() sets the day of the week

setDate() sets the day of the month as a number.

setFullYear() sets the 4 digit year.

setHours() sets the hours.

setMilliseconds() sets the milliseconds.

setMinutes() sets the minutes.

setMonth() sets the month.

setSeconds() sets the seconds.

setTime() sets the timestamp.

Conclusion

JavaScript comes with various operators and the Date constructor to let us create, get, and set dates.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *